package com.china.utils;

import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutionException;

/**
 * Created by Administrator on 2016/5/9.
 */
public class HttpUtils {

    public static String post(final String urls) {
        StringBuffer buffer = new StringBuffer();
        try {
            URL url = new URL(urls);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setReadTimeout(3 * 1000);
            if (connection.getResponseCode() == 200) {
                InputStream is = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                String str;
                while ((str = reader.readLine()) != null) {
                    buffer.append(str);
                }
                connection.connect();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block,
            e.printStackTrace();
        }

        return buffer.toString();
    }

    public static String get(final String url) {
        MyAsyncTask task = new MyAsyncTask();
        String str = null;
        try {
            str = task.execute(url).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return str;
    }

    static class MyAsyncTask extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub
            StringBuffer buffer = new StringBuffer();
            try {
                URL url = new URL(params[0]);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setReadTimeout(3 * 1000);
                if (connection.getResponseCode() == 200) {
                    InputStream is = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                    String str;
                    while ((str = reader.readLine()) != null) {
                        buffer.append(str);
                    }
                    connection.connect();
                }
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block,
                e.printStackTrace();
            }
            return buffer.toString();
        }

    }

}
